package com.zllkj.mm.module.shopping.activity

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.alipay.sdk.app.PayTask
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.github.gzuliyujiang.wheelpicker.OptionPicker
import com.github.gzuliyujiang.wheelpicker.contract.OnOptionPickedListener
import com.kennyc.bottomsheet.BottomSheetListener
import com.kennyc.bottomsheet.BottomSheetMenuDialogFragment
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.zllkj.mm.MyApp
import com.zllkj.mm.R
import com.zllkj.mm.api.network.RetrofitHelper
import com.zllkj.mm.api.network.RxHelper
import com.zllkj.mm.api.network.subscriber.ProgressSubscriber
import com.zllkj.mm.base.BaseTitleFragment
import com.zllkj.mm.common.ClientConfig
import com.zllkj.mm.common.L
import com.zllkj.mm.databinding.ActivityOrderDetailBinding
import com.zllkj.mm.model.entity.GoodsVo
import com.zllkj.mm.model.entity.OrderDetailBean
import com.zllkj.mm.model.entity.WeChatPayResp
import com.zllkj.mm.module.shopping.fragment.OrderListItemFragment
import com.zllkj.mm.module.shopping.vm.OrderDetailActivityVM
import com.zllkj.mm.util.PayResult
import com.zllkj.mm.util.common.FormatUtil
import com.zllkj.mm.wxapi.WXPayEntryActivity
import kotlinx.android.synthetic.main.activity_order_detail.*
import kotlinx.android.synthetic.main.fragment_order_list.*
import kotlinx.android.synthetic.main.include_action_bar.*
import kotlinx.android.synthetic.main.layout_topbar.view.*
import java.math.BigDecimal
import java.util.HashMap
import kotlin.concurrent.thread

class OrderDetailFragment(val orderId:String) : BaseTitleFragment() {

    var vm = OrderDetailActivityVM()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        var binding = DataBindingUtil.inflate<ActivityOrderDetailBinding>(layoutInflater,R.layout.activity_order_detail,null,false)
        binding.orderDetailActVM = vm;
        mRootView = binding.root
        mRootView.tv_title_right.visibility = View.INVISIBLE
        mRootView.tv_title_center.text = "售后详情"
        mRootView.fl_title_left.setOnClickListener { removeFragment() }
        loadData()

        requireActivity().registerReceiver(weChatPayBr, IntentFilter().apply { addAction(WXPayEntryActivity.SUCCESS_PAY)
        addAction(WXPayEntryActivity.FAILED_PAY)})
        return mRootView
    }

    @SuppressLint("HandlerLeak")
    private val mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                1-> {
                    val payResult = PayResult(msg.obj as Map<String?, String?>)
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo: String = payResult.getResult() // 同步返回需要验证的信息
                    val resultStatus: String = payResult.getResultStatus()
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        L.showToast("支付成功")
                        removeFragment()
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        L.showToast("支付失败")
                    }
                }
            }
        }
    }

    override fun onDetach() {
        super.onDetach()

    }

    override fun loadData() {
        super.loadData()

        addSubscribe(RetrofitHelper.getInstance().orderApi.getOrderDetail((HashMap<String, Any>().apply {
            this["orderId"] = orderId
        })).compose<OrderDetailBean>(RxHelper.defaultHandleResult<OrderDetailBean>()).subscribe(object : ProgressSubscriber<OrderDetailBean>(requireContext()){
            override fun onSucc(t: OrderDetailBean?) {
                vm.orderId.set(t?.orderNo)
                vm.name.set(t?.receiverName)
                vm.createTime.set(t?.createTime)
                vm.phoneNumber.set(t?.receiverPhone)
                vm.name.set(t?.shopName)
                vm.address.set(t?.province + t?.city + t?.district + "" + t?.detailAddress)
                vm.totalPrice.set( "¥" + FormatUtil.bigDecimalUtilFormat(t?.totalPrice.toString(),"100"))
                vm.shippingMoney.set("¥" +  FormatUtil.bigDecimalUtilFormat(t?.deliveryMode.toString(),"100"))
                loadDifferentStage(t?.orderStage)

                t?.goodsVoList?.let {
                    var adapter = object : BaseQuickAdapter<GoodsVo,BaseViewHolder>(R.layout.item_order_detail_each_one_goods,it){
                        override fun convert(p0: BaseViewHolder?, p1: GoodsVo?) {
                            p0?.getView<AppCompatTextView>(R.id.tv_order_detail_each_one_goods_count)?.text = "件数 * " + p1?.buyCount
                            Glide.with(mContext).load(ClientConfig.IMG_URL + p1?.goodsPic).into(p0?.getView<AppCompatImageView>(R.id.iv_order_detail_each_one_goods_image))
                            p0?.getView<AppCompatTextView>(R.id.tv_order_detail_each_one_goods_name)?.text = p1?.goodsName;
                            p0?.getView<AppCompatTextView>(R.id.tv_order_detail_each_one_goods_unitPrice)?.text = "¥" + BigDecimal(p1?.unitPrice.toString()).divide(BigDecimal("100")).toEngineeringString()
                        }
                    }
                    rv_order_detail_list_rv.layoutManager = object :LinearLayoutManager(requireContext()){
                        override fun canScrollVertically(): Boolean {
                            return false
                        }
                    }
                    rv_order_detail_list_rv.adapter = adapter
                }


            }

            override fun onError(e: Throwable?) {
                super.onError(e)
            }

        }))


    }

    override fun getContentLayoutId(): Int {
        return R.layout.activity_order_detail
    }

    fun loadDifferentStage(stage:Int?){
        when(stage) {
            OrderListItemFragment.ORDER_WAIT_TO_PAY -> {

                tv_clicked_2.visibility = View.VISIBLE
                tv_clicked_2.text = "取消订单"
                tv_clicked_2.setOnClickListener { orderDetailClickCancel() }
                tv_clicked_2.background = requireContext().getDrawable(R.drawable.strokegray_solid_gray_radius10)
                tv_clicked_2.setTextColor(Color.parseColor("#7B7B7B"))
                tv_clicked_3.visibility = View.VISIBLE
                tv_clicked_3.background = requireContext().getDrawable(R.drawable.strokegray_solid_ff5421_radius10)
                tv_clicked_3.setTextColor(Color.parseColor("#FF5421"))
                tv_clicked_3.setOnClickListener { orderDetailClickPay() }
                tv_clicked_3.text = "付款"
            }
            OrderListItemFragment.ORDER_WAIT_TO_SHIPPING -> {
                tv_clicked_2.visibility = View.GONE
                tv_clicked_2.text = "取消订单"
                tv_clicked_2.setOnClickListener {  }
                tv_clicked_2.background = requireContext().getDrawable(R.drawable.strokegray_solid_gray_radius10)
                tv_clicked_2.setTextColor(Color.parseColor("#7B7B7B"))
                tv_clicked_3.visibility = View.VISIBLE
                tv_clicked_3.background = requireContext().getDrawable(R.drawable.strokegray_solid_ff5421_radius10)
                tv_clicked_3.setTextColor(Color.parseColor("#FF5421"))
                tv_clicked_3.setOnClickListener {  }
                tv_clicked_3.text = "提醒发货"
            }
            else -> {
                tv_clicked_2.visibility = View.VISIBLE
                tv_clicked_2.text = "取消订单"
                tv_clicked_2.setOnClickListener { orderDetailClickCancel() }
                tv_clicked_2.background = requireContext().getDrawable(R.drawable.strokegray_solid_gray_radius10)
                tv_clicked_2.setTextColor(Color.parseColor("#7B7B7B"))
                tv_clicked_3.visibility = View.GONE
                tv_clicked_3.background = requireContext().getDrawable(R.drawable.strokegray_solid_ff5421_radius10)
                tv_clicked_3.setTextColor(Color.parseColor("#FF5421"))
                tv_clicked_3.setOnClickListener {  }
                tv_clicked_3.text = "提醒发货"
            }
        }
    }


    fun orderDetailClickCancel(){
        addSubscribe(RetrofitHelper.getInstance().orderApi.cancelOrder((HashMap<String, Any>().apply {
            this["cancelReason"] = ""
            this["orderId"] = orderId
        })).compose<String>(RxHelper.defaultHandleResult<String>()).subscribe(object : ProgressSubscriber<String>(requireContext()){
            override fun onSucc(t: String?) {
                L.showToast("取消成功")
                removeFragment()
            }

            override fun onError(e: Throwable?) {
                super.onError(e)
                L.showToast("取消订单失败")
            }
        }))
    }

    fun orderDetailClickPay(){

        var listener = object : BottomSheetListener{
            override fun onSheetDismissed(bottomSheet: BottomSheetMenuDialogFragment, `object`: Any?, dismissEvent: Int) {

            }

            override fun onSheetItemSelected(bottomSheet: BottomSheetMenuDialogFragment, item: MenuItem, `object`: Any?) {
                if(item.itemId == R.id.menu_alipay) {
                    getPayData(0,orderId)
                } else {
                    getPayData(1,orderId)
                }
            }

            override fun onSheetShown(bottomSheet: BottomSheetMenuDialogFragment, `object`: Any?) {

            }

        }
        BottomSheetMenuDialogFragment.Builder(context = requireContext(),
                sheet = R.menu.menu_pay_bottom_sheet,
                listener = listener,
                title = "请选择支付方式",
                `object` = "")
                .show(childFragmentManager)


    }
    fun getPayData(payType:Int,orderId:String){
        if (payType == 0) {
            addSubscribe(RetrofitHelper.getInstance().orderApi.getAliPayOrderInfo((HashMap<String, Any>().apply {
                this["orderIds"] = orderId
                this["orderSource"] = 0
            })).compose<String>(RxHelper.defaultHandleResult<String>()).subscribe(object : ProgressSubscriber<String>(requireContext()){
                override fun onSucc(t:String) {
                    thread {
                        kotlin.run {
                            Thread.sleep(300)
                            val alipay = PayTask(requireActivity())
                            val result = alipay.payV2(t, true)

                            val msg = Message()
                            msg.what = 1
                            msg.obj = result
                            mHandler.sendMessage(msg)
                        }
                    }.start()
                }
                override fun onError(e: Throwable?) {
                    super.onError(e)
                }
            }))
        } else {
            addSubscribe(RetrofitHelper.getInstance().orderApi.getWeChatPayOrderInfo((HashMap<String, Any>().apply {
                this["orderIds"] = orderId
                this["orderSource"] = 0
            })).compose<WeChatPayResp>(RxHelper.defaultHandleResult<WeChatPayResp>()).subscribe(object : ProgressSubscriber<WeChatPayResp>(requireContext()){
                override fun onSucc(t: WeChatPayResp) {
                    thread {
                        var req = PayReq()
                        req.timeStamp = t?.timestamp
                        req.sign = t?.sign
                        req.appId = MyApp.wxAppId
                        req.prepayId = t?.prepayid
                        req.packageValue = "Sign=WXPay"
                        req.nonceStr = t?.noncestr
                        req.partnerId = t?.partnerid
                        val api = WXAPIFactory.createWXAPI(requireContext(), null, false)
                        api.sendReq(req)
                    }.start()

                }
                override fun onError(e: Throwable?) {
                    super.onError(e)
                }
            }))
        }
    }

    var weChatPayBr = object : BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            when(intent?.action) {
                WXPayEntryActivity.Companion.SUCCESS_PAY -> {
                    removeFragment()
                }
            }
        }

    }
}